<template>
  <!--  面包屑-->
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>设备分类</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="row-play">
      分类状态：
      <el-select class="row-play-p" v-model="statusValue" placeholder="请选择">
        <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
      分类名称：
      <el-input class="row-play-play" v-model="name" placeholder="请输入内容"></el-input>
      <el-button class="row-play-p" @click="getPage">搜索</el-button>
      <el-button class="row-play-p" @click="add">新增</el-button>
      <el-button class="row-play-p" @click="toggleSelection()">取消选择</el-button>
      <el-button @click="deleteMany" type="danger">批量删除</el-button>
    </div>
    <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          label="修改时间"
          width="180">
        <template slot-scope="scope">{{ scope.row.updateTime }}</template>
      </el-table-column>
      <el-table-column
          label="分类名称"
          width="120">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p>创建人：{{ scope.row.createUserName }}</p>
            <p>创建时间: {{ scope.row.createTime }}</p>
            <p>修改人: {{ scope.row.updateUserName }}</p>
            <p>修改时间: {{ scope.row.updateTime }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ scope.row.name }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
          label="状态"
          width="100">
        <template slot-scope="scope">
          <el-switch
              @change="editStatus(scope.row)"
              style="display: block;height: 30px;"
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="handleEdit(scope.row)">修改名称
          </el-button>
          <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalSize">
      </el-pagination>
    </div>
    <el-dialog title="新增设备分类" :visible.sync="dialogFormVisible">
      <el-form ref="formRef" :model="form" :rules="formRules">
        <el-form-item label="分类名称" :label-width="formLabelWidth" style="width: 400px" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" ></el-input>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth" >
          <el-select v-model="form.status">
            <el-option label="上线" :value="1"></el-option>
            <el-option label="下线" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCategory">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

export default {
  data() {
    return {
      statusList: [{
        value: 0,
        label: '下线'
      }, {
        value: 1,
        label: '在线'
      }, {
        value: null,
        label: ''
      }],
      statusValue: null,
      name: '',
      tableData: [],
      multipleSelection: [],
      currentPage: 1,
      pageSize: 10,
      totalSize: 0,
      dialogFormVisible: false,
      formLabelWidth: '120px',
      form: {
        name: '',
        status: 0
      },
      formRules: {
        name: [{required: true, message: '请输入分类名称', trigger: 'blur'},
          {min: 1, max: 15, message: '长度在一到十五个字符之间', trigger: 'blur'}]
      }
    }
  },
  methods: {
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async () => {
        const {data: res} = await this.$http.delete("/category/" + row.id);
        if (res.code === 0) {
          return this.$message.error(res.msg);
        }
        await this.getPage();
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getPage();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getPage();
    },
    async getPage() {
      const {data: res} = await this.$http.get("/category/page", {
        params: {
          page: this.currentPage,
          pageSize: this.pageSize,
          status: this.statusValue,
          name: this.name
        }
      });
      if (res.code === 0) {
        return this.$message.error("获取设备分类信息失败");
      }
      this.tableData = res.data.records;
      this.totalSize = res.data.total;
    },
    async editStatus(row) {
      this.$refs.multipleTable.doLayout();
      const {data: res} = await this.$http.put("/category/updateStatus",{
        id:row.id,
        status:row.status
      });
      if (res.code === 0) {
        await this.getPage();
        return this.$message.error(res.msg);
      }
      this.$message({
        type: 'success',
        message: '修改成功!'
      });
    },
    deleteMany() {
      let ids = [];
      this.multipleSelection.forEach(row => {
        ids.push(row.id);
      })
      let idss = ids.join(',');
      this.$confirm('此操作将永久删除多个分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async () => {
        const {data: res} = await this.$http.delete("/category", {
          params: {
            ids: idss
          }
        });
        if (res.code === 0) {
          return this.$message.error(res.msg);
        }
        await this.getPage();
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    add() {
      this.dialogFormVisible = true;
    },
    addCategory() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return false;
        this.dialogFormVisible = false;
        const {data: res} = await this.$http.post("/category/add", this.form);
        if (res.code === 0) {
          return this.$message.error(res.msg);
        }
        await this.getPage();
        this.$message.success("添加成功");
      })
    },
    handleEdit(row) {
      this.$prompt('请输入名称', '修改名称', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.{1,15}$/,
        inputErrorMessage: '字符长度必须在1到15之间',
        inputValue:row.name
      }).then(async ({value}) => {
        const {data: res} = await this.$http.put("/category/updateName",{
          id:row.id,
          name:value
        });
        if(res.code===0)return this.$message.error(res.msg);
        this.$message({
          type: 'success',
          message: '修改成功'
        });
        await this.getPage();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    }
  },
  mounted() {
    this.getPage();
  }
}
</script>

<style scoped lang="less">
.row-play {
  display: flex;
  align-items: center;

  .row-play-play {
    width: 200px;
    margin-right: 20px;
  }

  .row-play-p {
    margin-right: 20px;
  }
}

.block {
  text-align: center;
}
</style>